﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.Common;
using System.Drawing;
using LTP.Accounts.Bus;
using System.IO;
namespace lcs.Web.demandmaterialinfo
{
    public partial class List : Web.Admin.BasePage
    {
        lcs.BLL.demandmaterialinfo bll = new lcs.BLL.demandmaterialinfo();
        public string type;
        public string idstr;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //gridView.BorderColor = ColorTranslator.FromHtml(Application[Session["Style"].ToString() + "xtable_bordercolorlight"].ToString());
                //gridView.HeaderStyle.BackColor = ColorTranslator.FromHtml(Application[Session["Style"].ToString() + "xtable_titlebgcolor"].ToString());
                if (Request.QueryString["id"] != null && Request.QueryString["id"].ToString() != "" && Request.QueryString["type"] != null && Request.QueryString["type"].ToString() != "")
                {
                    int id = 0;
                    int.TryParse(Request.QueryString["id"].ToString(), out id);
                    idstr = id.ToString();
                    type = Request.QueryString["type"].ToString();
                    if (type != "0")
                    {
                        int typenum = 0;
                        int.TryParse(type, out typenum);
                        //BLL.pmtypeinfo pb = new BLL.pmtypeinfo();
                        //string name = pb.GetModel(typenum).pmtype;
                        if (typenum>40)
                        {
                            BLL.demandplaninfo bllde = new BLL.demandplaninfo();
                            DataSet ds=bllde.GetList(" and dpid="+id);
                            if (ds.Tables[0].Rows.Count == 1)
                            {
                                string mtidstr = ds.Tables[0].Rows[0]["mtid"].ToString();
                                string sidstr = ds.Tables[0].Rows[0]["sid"].ToString();
                                int mtid = 0, sid = 0;
                                int.TryParse(mtidstr, out mtid);
                                int.TryParse(sidstr, out sid);
                                int depid=getdepid();
                                BLL.protocolquotainfo pb = new BLL.protocolquotainfo();
                                decimal aq=pb.Getquota(depid,mtid,sid);
                                BLL.demandmaterialinfo db=new BLL.demandmaterialinfo();
                                decimal iq=db.Getquota(depid,mtid,sid);
                                lblxy.Text = "物料类型：" + ds.Tables[0].Rows[0]["mtname"].ToString() + " 供应商：" + ds.Tables[0].Rows[0]["xysname"].ToString() + " 总配额为：" + aq.ToString("F2") + " 已用配额为：" + iq.ToString("F2") + " 剩余配额为：" + (aq - iq).ToString("F2");
                                
                                hladd.NavigateUrl = string.Format("Addxy.aspx?id={0}&type={1}&mtid={2}&sid={3}", id, type, mtid, sid);
                                pxy.Visible = true;
                            }
                            else
                            {
                                Maticsoft.Common.MessageBox.ShowAndRedirect(this, "页面参数不对！", "../demandplaninfo/List.aspx");

                            }

                        }
                        else
                        {                        
                            ddlrecom.Visible = true;
                            btnre.Visible = true;
                            BLL.bidsupplyinfo bbll = new BLL.bidsupplyinfo();
                            string sql = " and mtype='" + type + "'";
                            int aid = getaid();
                            if (aid != 0) sql += " and aid=" + aid;
                            DataSet ds = bbll.GetList(sql);
                            ddlrecom.DataSource = ds;
                            ddlrecom.DataValueField = "sid";
                            ddlrecom.DataTextField = "sname";
                            ddlrecom.DataBind();
                            hladd.NavigateUrl = string.Format("Add.aspx?id={0}&type={1}", id, type);
                        }
                    }
                    else
                    {
                        precom.Visible = false;
                        hladd.NavigateUrl = string.Format("Add.aspx?id={0}&type={1}", id, type);
                    }
                    btnDelete.Attributes.Add("onclick", "return confirm(\"你确认要删除吗？\")");
                    
                    BindData();
                }
                else
                {
                    Maticsoft.Common.MessageBox.ShowAndRedirect(this, "页面参数不对！", "../demandplaninfo/List.aspx");
                }
                Page.DataBind();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string idlist = GetSelIDlist();
            if (idlist.Trim().Length == 0)
                return;
            bll.DeleteList(idlist);
            BindData();
        }

        #region gridView

        public void BindData()
        {
            if (Request.QueryString["id"] != null && Request.QueryString["id"].ToString() != "")
            {
                int id = 0;
                int.TryParse(Request.QueryString["id"].ToString(), out id);
                DataSet ds = new DataSet();
                StringBuilder strWhere = new StringBuilder();
                if (txtKeyword.Text.Trim() != "")
                {
                    strWhere.AppendFormat(" and mms like '%{0}%'", txtKeyword.Text.Trim());
                }
                strWhere.AppendFormat("and dpid='{0}'", id);
                ds = bll.GetList(strWhere.ToString());
                gridView.DataSource = ds;
                gridView.DataBind();
            }
        }

        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }
        protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //e.Row.Cells[0].Text = "<input id='Checkbox2' type='checkbox' onclick='CheckAll()'/><label></label>";
            }
        }
        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Attributes.Add("style", "background:#FFF");
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton linkbtnDel = (LinkButton)e.Row.FindControl("LinkButton1");
                linkbtnDel.Attributes.Add("onclick", "return confirm(\"你确认要删除吗\")");
                HyperLink hl1 = (HyperLink)e.Row.FindControl("HyperLink1");
                if (hl1 != null)
                {
                    hl1.NavigateUrl += string.Format("&id={0}&type={1}", idstr, type);
                }
            }
        }

        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //#warning 代码生成警告：请检查确认真实主键的名称和类型是否正确
            int ID = (int)gridView.DataKeys[e.RowIndex].Value;
            bll.Delete(ID);
            BindData();
        }

        private string GetSelIDlist()
        {
            string idlist = "";
            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("DeleteThis");
                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));
            }
            return idlist;
        }

        #endregion

        protected void btnre_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null && Request.QueryString["id"].ToString() != "" && Request.QueryString["type"] != null && Request.QueryString["type"].ToString() != "")
            {
                int id = 0;
                int.TryParse(Request.QueryString["id"].ToString(), out id);
                idstr = id.ToString();
                type = Request.QueryString["type"].ToString();
                int reid = int.Parse(ddlrecom.SelectedValue);
                if (type != "0")
                {
                    BLL.demandplaninfo dbll = new BLL.demandplaninfo();
                    if (dbll.SetRecomsup(reid, id))
                        Maticsoft.Common.MessageBox.Show(this, "设置应用类推荐厂家成功！");
                    else
                        Maticsoft.Common.MessageBox.Show(this, "设置失败！");

                }
            }
        }

        protected void btnfile_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null && Request.QueryString["id"].ToString() != "" && Request.QueryString["type"] != null && Request.QueryString["type"].ToString() != "")
            {
                int id = 0;
                int.TryParse(Request.QueryString["id"].ToString(), out id);
                idstr = id.ToString();
                type = Request.QueryString["type"].ToString();

                string orifilename = string.Empty;
                string uploadfilepath = string.Empty;
                string modifyfilename = string.Empty;
                string fileExtend = "";//文件扩展名
                try
                {
                    if (fufile.HasFile && fufile.PostedFile != null)
                    {
                        //得到文件的大小
                        int fileSize = fufile.PostedFile.ContentLength;
                        if (fileSize == 0)
                        {
                            Maticsoft.Common.MessageBox.Show(this, "导入的文件大小为0，请检查是否正确！");
                        }
                        //得到扩展名
                        orifilename = fufile.PostedFile.FileName;
                        fileExtend = orifilename.Substring(orifilename.LastIndexOf(".") + 1);
                        //if (fileExtend.ToLower() != "doc")
                        //{
                        //    throw new Exception("你选择的文件格式不正确，只能导入EXCEL文件！");
                        //}
                        //路径
                        uploadfilepath = Server.MapPath("~/upload/");
                        //新文件名
                        modifyfilename = System.Guid.NewGuid().ToString();
                        //modifyfilename = inputfile.PostedFile.FileName;
                        modifyfilename += "." + fileExtend;
                        //判断是否有该目录
                        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);
                        if (!dir.Exists)
                        {
                            dir.Create();
                        }
                        if (!uploadfilepath.EndsWith("\\"))
                            orifilename = uploadfilepath + "\\" + modifyfilename;
                        else
                            orifilename = uploadfilepath + modifyfilename;
                        //如果存在,删除文件
                        if (File.Exists(orifilename))
                        {
                            File.Delete(orifilename);
                        }
                        // 上传文件
                        fufile.PostedFile.SaveAs(orifilename);
                        BLL.demandplaninfo dbll = new BLL.demandplaninfo();

                        if (dbll.SetFile("/upload/" + modifyfilename, id))
                            Maticsoft.Common.MessageBox.Show(this, "设置技术文档成功！");
                        else
                            Maticsoft.Common.MessageBox.Show(this, "设置失败！");
                    }
                    else
                    {
                        throw new Exception("请选择要导入的Excel文件!");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

        }
    }
}
